<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="pd.showSearch">
        <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="客户名称" prop="partnerId">
            <PartnerSearch ref="searchRef" :dataText="pd.queryParams.partnerName" :params="{isCustomer:true}" title="请选择查询客户"
                           @ok="searchCustomer2($event)" @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="单据状态" prop="status">
            <dictSelect :dictType="'wms_order_status'" v-model:dict-value="pd.queryParams.status"/>
          </el-form-item>
          <el-form-item label="更新时间" style="width: 290px">
            <el-date-picker
              v-model="dateRangeUpdateTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
              range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
          </el-form-item>
          <el-form-item>
          </el-form-item>
        </el-form>
      </div>
    </transition>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wms:order:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wms:order:export']">导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="pd.loading" :data="pd.orderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <!--        <el-table-column label="主键" align="center" prop="id" v-if="true"/>-->
        <el-table-column label="单据类别" align="center" prop="typeName"/>
        <el-table-column label="名称" align="center" prop="name">
          <template #default="scope">
            <el-link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['wms:order:edit']">
              {{ scope.row.name }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="客户名称" align="center" prop="partnerName"/>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dictTag :options="wms_order_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="总金额" align="center" prop="totalMoney"/>
        <el-table-column label="优惠金额" align="center" prop="discountMoney"/>
        <el-table-column label="实际金额" align="center" prop="costMoney"/>
        <el-table-column label="来源单号" align="center" prop="sourceId"/>
        <el-table-column label="退回单号" align="center" prop="backId"/>
        <el-table-column label="申请人" align="center" prop="applicantId"/>
        <el-table-column label="操作人" align="center" prop="execId"/>
        <el-table-column label="备注" align="center" prop="remark"/>
        <el-table-column fixed="left" label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template #default="scope">

            <el-button link type="primary" icon="Finished" @click="handleExecOrder(scope.row)"
                       v-if="scope.row.status === '1'" v-hasPermi="['wms:order:edit']"> 执行
            </el-button>
            <el-button link type="primary" icon="Check"
                       v-if="scope.row.status === '0'" v-hasPermi="['wms:order:edit']"> 完成
            </el-button>
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-if="scope.row.status === '1'" v-hasPermi="['wms:order:edit']"> 修改
            </el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row.id)"
                       v-if="scope.row.status === '1'" v-hasPermi="['wms:order:remove']">删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>
      <Pagination v-show="pd.total>0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                  v-model:limit="pd.queryParams.pageSize" @pagination="getList"/>
    </el-card>
    <!-- 添加或修改测试主从对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="1000" append-to-body>
      <el-form ref="orderFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户名称" prop="partnerId">
              <PartnerSearch ref="searchRef"  :dataText="pd.form.partnerName" :params="{isCustomer:true}" @ok="searchCustomer1($event)"/>
            </el-form-item>
            <el-form-item label="选择仓库" prop="selfWhId">
              <WarehouseSelect :disabled="pd.warehouseSelectLock" :params="{parentId:0}" v-model:whId="pd.form.selfWhId" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据名称" prop="name">
              <el-input v-model="pd.form.name" placeholder="请输入单据名称"/>
            </el-form-item>
            <el-form-item label="退款账户" prop="fmsAccount">
              <el-select v-model="pd.form.fmsAccount">
                <el-option v-for="item in pd.FmsAccountList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <DictSelect disabled :dictType="'wms_order_status'" v-model:dictValue="pd.form.status"/>
            </el-form-item>
            <el-form-item label="零售订单" prop="status">
              <OrderSearch :is-show="false" :searchType="1" :params="{isStock:true,typeId:14,selfWhId:pd.form.selfWhId != null?pd.form.selfWhId:null}" @ok="lineAdd2" title="零售订单" dataText="零售订单"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row :gutter="10" class="mb8">

        <el-col :span="1.5">
          <el-button v-if="!pd.form.id" icon="Plus" type="success" @click="submitForm">保存单据</el-button>
          <el-button v-if="pd.form.id" icon="Delete" type="danger" @click="handleDelete(pd.form.id)">删除单据</el-button>
        </el-col>
        <el-col v-if="pd.form.id" :span="1.5">
          <el-button icon="Plus" type="success" @click="submitForm">修改单据</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="Close" type="info" @click="pd.dialog.visible = false">关闭</el-button>
        </el-col>
        <el-col :span="1.5">
          <StockSearch :searchType="2" :params="{isStock:true,warehouseId:pd.form.selfWhId}" @ok="lineAdd" title="库存查询" dataText="新增一行" />
        </el-col>
        <el-col :span="1.5">
          <el-button icon="Refresh" @click="getLineList">刷新</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="pd.loading" :data="pd.form.line">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="物品名称" align="center" prop="productName"/>
        <el-table-column label="单位" align="center" prop="measureUnit" width="60"/>
        <el-table-column label="价格" align="center" prop="price" width="80"/>
        <el-table-column label="库存" align="center" prop="maxQuantity" width="80" />
        <el-table-column label="数量" align="center" prop="quantity" width="80">
          <template #default="scope">
            <el-input @input="computCostMoney(scope.row)" v-model="scope.row.quantity" placeholder="请输入数量" oninput="value=value.replace(/[^\d]/g, '')"/>
          </template>
        </el-table-column>

        <el-table-column label="总金额" align="center" prop="totalMoney" width="80"/>
        <el-table-column label="优惠金额" align="center" prop="quantity" width="120">
          <template #default="scope">
            <el-input @input="computCostMoney(scope.row)" v-model="scope.row.discountMoney" placeholder="请输入优惠金额" oninput="value=value.replace(/[^\d]/g, '')"/>
          </template>
        </el-table-column>
        <el-table-column label="应收金额" align="center" prop="costMoney" width="120">
          <template #default="scope">
            <el-input @input="computDiscountMoney(scope.row)" v-model="scope.row.costMoney" placeholder="应收金额" oninput="value=value.replace(/[^\d]/g, '')"/>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="180">
          <template #default="scope">
            <el-button link type="primary" icon="Delete" @click="delLine(scope.row)" v-hasPermi="['wms:order:del']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="pd.lineTotal>0" :total="pd.lineTotal" v-model:page="pd.queryLineParams.pageNum"
                  v-model:limit="pd.queryLineParams.pageSize" @pagination="getLineList"/>
    </el-dialog>

    <!-- 查看 -->
    <el-dialog :title="pd.inspectionDialog.title" v-model="pd.inspectionDialog.visible" width="1000">
      <el-descriptions>
        <el-descriptions-item label="供应商">{{ pd.form.partnerName }}</el-descriptions-item>
        <el-descriptions-item label="单据名称">{{ pd.form.name }}</el-descriptions-item>
        <el-descriptions-item label="单据编号">{{ pd.form.id }}</el-descriptions-item>
        <el-descriptions-item label="仓库">{{ pd.form.warehouseName }}</el-descriptions-item>
      </el-descriptions>
      <el-table :data="pd.form.line" stripe style="width: 100%">
        <el-table-column prop="productName" label="物品名称" width="120"/>
        <el-table-column prop="measureUnit" label="单位" width="120"/>
        <el-table-column prop="price" label="采购价" width="120" />
        <el-table-column prop="quantity" label="数量" width="120" />
        <el-table-column prop="totalMoney" label="总金额" width="120" />
        <el-table-column prop="discountMoney" label="优惠金额" width="120" />
        <el-table-column prop="costMoney" label="实际金额" />
      </el-table>
      <pagination class="print-hidden" v-show="pd.lineTotal>0" :total="pd.lineTotal" v-model:page="pd.queryLineParams.pageNum"
                  v-model:limit="pd.queryLineParams.pageSize" @pagination="getLineList"/>
      <el-col :span="1.5">
        <el-button class="print-hidden" style="float: inherit" type="primary" @click="print">打印</el-button>
      </el-col>
    </el-dialog>
  </div>
</template>

<script setup name="OrderRetail" lang="ts">
import {
  OrderLineVO, OrderVO, addOrder, backOrder, delOrder, delOrderLine, execOrder, listOrder, listOrderLine,
  updateOrder, getOrderType
} from '@/views/wms/order/api';
import {PartnerVO} from "@/views/hrp/partner/api";
import {AccountVO, listAccount} from "@/views/fms/account/api";
import PartnerSearch from '@/views/hrp/partner/search.vue';
import DictSelect from '@/views/system/dict/select.vue';
import WarehouseSelect from "@/views/wms/warehouse/select.vue";
import OrderSearch from "@/views/wms/order/search.vue";
import StockSearch from "@/views/wms/stock/search.vue";
import {StockVO} from "@/views/wms/stock/api";

const route = useRoute();
const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {wms_order_status} = toRefs<any>(proxy?.useDict('wms_order_status'));
const dateRangeUpdateTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const orderFormRef = ref<ElFormInstance>();
const searchRef = ref();

const pd = reactive({
  warehouseSelectLock: false,
  orderList: <OrderVO[]>([]),
  buttonLoading: false,
  loading: true,
  showSearch: true,
  total: 0,
  lineTotal: 0,
  backId: null,
  FmsAccountList: <AccountVO[]>([]),
  form: <OrderVO>{},
  dialog: <DialogOption>{
    visible: false,
    title: ''
  },
  queryParams: <OrderVO>{
    pageNum: 1,
    pageSize: 10
  },
  queryParams14: <OrderVO>{
    pageNum: 1,
    pageSize: 10,
    typeId: 14,
  },
  queryLineParams: <OrderLineVO>{
    pageNum: 1,
    pageSize: 10,
    id: undefined
  },
  rules: <ElFormRules>{
    typeId: [{required: true, message: "单据类别不能为空", trigger: "change"}],
    name: [{required: true, message: "单据名称不能为空", trigger: "blur"}],
    selfWhId: [{required: true, message: "仓库不能为空", trigger: "blur"}],
    status: [{required: true, message: "状态不能为空", trigger: "change"}],
    fmsAccount: [{required: true, message: "退款账户不能为空", trigger: "blur"}]
  },
  inspectionDialog: <DialogOption>{
    visible: false,
    title: '采购订单-详情'
  },
});

function print(){
  window.print();
}

function handleExecOrder(vo: OrderVO) {
  execOrder(vo).then(res => {
    resetQuery()
  });
}

function handleBackOrder(vo: OrderVO) {

  backOrder(vo).then(res => {
    proxy?.$modal.msg(res.msg)
  });
}

async function getFmsAccount(){
  pd.FmsAccountList = (await listAccount()).rows
}

function searchCustomer1(pVo: PartnerVO[]) {
  pVo.forEach((v, i, a) => {
    pd.form.partnerId = v.id;
    pd.form.partnerName = v.name;
    return;
  });
}

function searchCustomer2(pVo: PartnerVO[]) {
  pVo.forEach((v, i, a) => {
    pd.queryParams.partnerId = v.id;
    pd.queryParams.partnerName = v.name;
    return;
  });
}

/** 查询测试主从列表 */
async function getList() {
  pd.loading = true;
  pd.queryParams.params = {};
  proxy?.addDateRange(pd.queryParams, dateRangeUpdateTime.value, 'UpdateTime');
  const res = await listOrder(pd.queryParams);
  pd.orderList = res.rows;
  pd.total = res.total;
  pd.loading = false;
}

/** 查询测试子列表 */
function getLineList() {
  pd.loading = true;
  pd.queryLineParams.id = pd.form.id;
  listOrderLine(pd.queryLineParams).then(res => {
    pd.form.line = res.rows;
    pd.lineTotal = res.total;
    pd.loading = false;
  });
}

/** 表单重置 */
const reset = () => {
  pd.form = <OrderVO>{};
  pd.form.line = [];
  pd.form.typeId = pd.queryParams.typeId;
  orderFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRangeUpdateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  pd.queryParams.partnerName = '';
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: OrderVO[]) {
  // pd.selected = selection;
  // pd.single = selection.length != 1;
  // pd.multiple = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.form.status = '1';
  pd.dialog.title = "新增零售退货";
  pd.dialog.visible = true;
}

/** 新增一行按钮操作 */
async function lineAdd(vo: StockVO[]) {
  let line = <OrderLineVO>{};
  vo.forEach((v, i, a) => {
    line.productId = v.productId as number;
    line.productName = v.productName;
    line.price = v.price;
    line.measureUnit = v.measureUnit;
    line.quantity = 1;
    line.maxQuantity = v.quantity;
    line.totalMoney = v.price;
    line.discountMoney = 0;
    line.costMoney = line.totalMoney! - line.discountMoney;
    if (!checkAddList(pd.form.line!,v.productId!)){
      pd.form.line!.push(line);
    }

    pd.warehouseSelectLock = true;
    pd.form.selfWhId = v.warehouseId;
  });
}
watch(()=>pd.form.line,(value)=>{
  if (value != undefined && value.length == 0){
    pd.warehouseSelectLock = false;
    pd.form.selfWhId = undefined;
  }
},{deep:true})

/** 新增多行按钮操作 */
async function lineAdd2(vo: OrderVO) {
  const data = JSON.parse(JSON.stringify(vo))
  let line: OrderLineVO = {};
  line.id = data[0].id;
  line.whId = data[0].selfWhId;
  let res: OrderLineVO[] = [];
  await listOrderLine(line).then((result)=>{
    res = result.rows;
  });
  pd.form.selfWhId = data[0].selfWhId;
  res.forEach((v, i, a) => {
    line.id = v.id;
    line.productId = v.productId;
    line.productName = v.productName;
    line.price = v.price ? v.price : 0;
    line.measureUnit = v.measureUnit;
    line.quantity = 1;
    line.maxQuantity = v.stockQuantity;
    line.totalMoney = v.price ? v.price : 0;
    line.discountMoney = v.discountMoney ? v.discountMoney : 0;
    line.costMoney = line.discountMoney ? line.totalMoney - line.discountMoney : line.totalMoney * line.quantity;
    line.whName = data.warehouseName;
    line.whId = data.warehouseId;
    if (!checkAddList(pd.form.line!,v.productId!)){
      pd.form.line!.push(line);
    }
    line = {};
  });
}

function checkAddList(lineList: OrderLineVO[],lineId: number | string){
  const found = lineList.find(item => item.productId == lineId);
  if (found ){
    lineList.forEach((v, i)=>{
      if (v.productId == lineId && pd.form.line){
        pd.form.line[i].totalMoney = pd.form.line[i].totalMoney / pd.form.line[i].quantity + pd.form.line[i].totalMoney ;
        pd.form.line[i].costMoney = pd.form.line[i].totalMoney - pd.form.line[i].discountMoney ;
        console.log("totalMomey: ",pd.form.line[i].totalMoney)
        pd.form.line[i].quantity = parseInt(pd.form.line[i].quantity) + 1 ;
      }
    })
  }
  return found
}

// 计算金额
function computCostMoney(vo: OrderLineVO) {
  vo.totalMoney = vo.quantity! * vo.price!;
  vo.costMoney = vo.totalMoney - vo.discountMoney!;
}

// 计算金额
function computDiscountMoney(vo: OrderLineVO) {
  vo.totalMoney = vo.quantity! * vo.price!;
  vo.discountMoney = vo.totalMoney - vo.costMoney!;
}

/** 修改按钮操作 */
async function handleUpdate(row?: OrderVO) {
  // const vo = row || pd.selected[0]
  Object.assign(pd.form, row);
  getLineList();
  if (row?.status == "0"){
    pd.inspectionDialog.visible = true;
    pd.inspectionDialog.title = '零售退货-详情';
    return
  }
  pd.dialog.visible = true;
  pd.dialog.title = "修改零售退货";
}

/** 提交按钮 */
function submitForm() {
  orderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.form.wmsType = "in";
      if (pd.form.id) {
        pd.buttonLoading = true;
        await updateOrder(pd.form).then((res: any) => {
          pd.buttonLoading = false
          proxy?.$modal.msgSuccess(res.msg);
        });
      } else {
        await addOrder(pd.form).then((res: any) => {
          pd.buttonLoading = false
          proxy?.$modal.msgSuccess(res.msg);
        });
      }
      pd.dialog.visible = false;
      await getList();
    }
  })
}

/** 删除按钮操作 */
async function handleDelete(id: number) {
  await proxy?.$modal.confirm('是否确认删除测试主从编号为"' + id + '"的数据及子数据？').finally(() => pd.loading = false);
  await delOrder(id as number);
  proxy?.$modal.msgSuccess("删除成功");
  pd.dialog.visible = false;
  await getList();
}

/** 删除子表操作 */
async function delLine(row: OrderLineVO) {
  if (row.lineId === undefined) {
    const index = pd.form.line!.indexOf(row);
    pd.form.line!.splice(index, 1);
    return;
  }

  proxy?.$modal.confirm('是否确认删除 子单号为:"' + row.lineId + '"的数据项？').then(function () {
    return delOrderLine(row.lineId as number);
  }).then(() => {
    const index = pd.form.line!.indexOf(row);
    pd.form.line!.splice(index, 1);
    proxy.$modal.msgSuccess("删除成功");
    // getLineList();
  }).catch(() => {
  });

}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('demo/order/export', {
    ...pd.queryParams
  }, `order_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  pd.queryParams.typeId = Number(route.query.typeId as unknown);
  pd.form.typeId = Number(route.query.typeId as unknown);
  if (route.query.status)
    pd.queryParams.status = route.query.status as string;
  if (route.query.beginUpdateTime && route.query.endUpdateTime) {
    dateRangeUpdateTime.value = [route.query.beginUpdateTime as string + " 00:00:00",route.query.endUpdateTime as string + " 00:00:00"];
  }
  getList();
  getFmsAccount();
});
</script>
